# -*- coding: utf-8 -*-
"""
@File:    codecs.py
@Author:  jk.dong
@Desc:    字符处理相关方法
"""
import chardet
from email.header import decode_header
import logging


def detect_charset(msg):
    """获取邮件的字符编码，首先在message中寻找编码，如果没有，就在header的Content-Type中寻找"""
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    charset = gb2312_to_gb18030(charset)
    return charset


def guess_charset(binary_data, default_charset):
    """
    使用chardet库猜测二进制数据编码.
    1、几率大于0.5以上时可以认为检测编码类型为准确.
    2、为兼容长江证券报告解析，将字符集检测confidence从0.5改为0.4
    """
    if chardet.detect(binary_data)['confidence'] > 0.4:
        default_charset = chardet.detect(binary_data)['encoding']
    return gb2312_to_gb18030(default_charset)


def gb2312_to_gb18030(charset):
    """gb2312无法解析罕见字,所以将gb2312改为gb18030"""
    if isinstance(charset, str) and (charset.lower() == 'gb2312' or charset.lower() == 'gbk'):
        return 'gb18030'
    else:
        return charset


def decode_str(string_):
    """解析消息头中的字符串"""
    if len(decode_header(string_)) > 1:
        values = ""
        for value, charset in decode_header(string_):
            charset = gb2312_to_gb18030(charset)
            if charset:
                value = value.decode(charset)
            else:
                if type(value) is bytes:
                    value = value.decode()
            if type(value) is str:
                values += value
            else:
                logging.info(f"参数为:{string_}\t不解码。")
        return values
    else:
        value, charset = decode_header(string_)[0]
        charset = gb2312_to_gb18030(charset)
        if charset:
            value = value.decode(charset)
        else:
            if type(value) is bytes:
                value = value.decode()
        if type(value) is not str:
            value = ""
            logging.info(f"参数为:{string_}\t不解码。")
    return value

